import db from './database';
import { novelsApi } from '../services/api';

// 避免循环依赖的辅助函数
const safeDbCall = async (table, callback) => {
  try {
    if (!db[table]) {
      console.error(`表 ${table} 不存在或未初始化`);
      return null;
    }
    return await callback();
  } catch (err) {
    console.error(`数据库操作失败 (${table}):`, err);
    return null;
  }
};

/**
 * 小说操作
 */
export const novelOperations = {
  // 添加或更新小说
  async addOrUpdateNovel(novel) {
    return await safeDbCall('novels', async () => db.novels.put(novel));
  },

  // 获取所有小说
  async getAllNovels() {
    return await safeDbCall('novels', async () => db.novels.toArray()) || [];
  },

  // 获取单本小说
  async getNovel(id) {
    return await safeDbCall('novels', async () => db.novels.get(id));
  },

  // 删除小说及相关数据
  async deleteNovel(id) {
    return await safeDbCall('all-tables', async () => {
      console.log(`开始删除小说: ${id}`);
      
      // 使用事务确保数据完整性
      await db.transaction('rw', [
        db.novels, 
        db.chapters, 
        db.fullContents, 
        db.readingProgress, 
        db.cacheInfo
      ], async () => {
        // 1. 删除阅读进度
        console.log(`删除小说 ${id} 的阅读进度...`);
        await db.readingProgress.where('novelId').equals(id).delete();
        
        // 2. 删除章节
        console.log(`删除小说 ${id} 的章节...`);
        await db.chapters.where('novelId').equals(id).delete();
        
        // 3. 删除完整内容
        console.log(`删除小说 ${id} 的完整内容...`);
        await db.fullContents.where('novelId').equals(id).delete();
        
        // 4. 删除缓存信息
        console.log(`删除小说 ${id} 的缓存信息...`);
        await db.cacheInfo.where('novelId').equals(id).delete();
        
        // 5. 最后删除小说本身
        console.log(`删除小说 ${id} 的主记录...`);
        await db.novels.delete(id);
      });
      
      console.log(`小说 ${id} 已完全删除`);
      return { status: 'success', id };
    });
  },

  // 缓存小说内容
  async cacheNovel(novel, content) {
    try {
      if (!novel || !novel.id || !content) {
        console.error('缓存小说参数无效', { novel, contentLength: content?.length });
        throw new Error('缓存小说参数无效');
      }
      
      return await safeDbCall('novels', async () => {
        // 开始事务
        await db.transaction('rw', [db.novels, db.fullContents, db.cacheInfo], async () => {
          // 1. 更新小说表，标记为已缓存
          await db.novels.update(novel.id, { cached: true, lastCached: Date.now() });
          
          // 2. 存储整本小说内容到fullContents表
          await db.fullContents.put({
            novelId: novel.id,
            data: content,
            timestamp: Date.now()
          });
          
          // 3. 更新缓存信息
          await db.cacheInfo.put({
            novelId: novel.id,
            lastCached: Date.now(),
            complete: true
          });
          
          console.log(`小说 "${novel.name}" (ID: ${novel.id}) 缓存完成`);
        });
        
        return { status: 'success', novelId: novel.id };
      });
    } catch (err) {
      console.error(`缓存小说失败: ${novel?.name || novel?.id}`, err);
      throw err;
    }
  },

  // 更新缓存信息 - 增加错误处理
  async updateCacheInfo(novelId, info) {
    return await safeDbCall('cacheInfo', async () => {
      const cacheInfo = await db.cacheInfo.get(novelId) || { novelId };
      const updatedInfo = { ...cacheInfo, ...info };
      await db.cacheInfo.put(updatedInfo);
      return updatedInfo;
    });
  },

  // 获取缓存信息
  async getCacheInfo(novelId) {
    return await safeDbCall('cacheInfo', async () => 
      await db.cacheInfo.get(novelId) || { novelId, complete: false }
    );
  },

  // 检查小说是否已缓存
  async isNovelCached(id) {
    try {
      const novel = await this.getNovel(id);
      if (!novel) return false;
      
      // 修复数字转换问题
      const numericId = typeof id === 'string' ? parseInt(id, 10) : id;
      
      // 检查cached标记和fullContents表
      if (novel.cached) {
        // 使用filter查询，与diagnoseNovelStorage保持一致
        const fullContents = await safeDbCall('fullContents', async () => 
          await db.fullContents
            .filter(item => item.novelId == numericId)
            .toArray()
        ) || [];
        
        const fullContent = fullContents && fullContents.length > 0 ? fullContents[0] : null;
        
        if (fullContent && fullContent.data && fullContent.data.length > 0) {
          return true;
        }
        
        // 如果cached为true但实际上没有内容，修复数据不一致
        console.warn(`小说 ${id} 被标记为已缓存，但未找到缓存内容。修复数据不一致...`);
        await safeDbCall('novels', async () => {
          await db.novels.update(id, { cached: false });
        });
        
        return false;
      }
      
      return false;
    } catch (err) {
      console.error(`检查小说缓存状态失败: ${id}`, err);
      return false;
    }
  },

  // 获取小说缓存内容
  async getNovelContent(id) {
    try {
      console.log(`尝试获取小说 ${id} 的缓存内容`);
      console.log(`Debug: getNovelContent被调用，开始从IndexedDB数据库获取小说内容`);
      
      // 修复数字转换问题
      const numericId = typeof id === 'string' ? parseInt(id, 10) : id;
      console.log(`转换后的数字ID: ${numericId}, 原始ID类型: ${typeof id}`);
      
      console.log(`开始查询fullContents表中novelId=${numericId}的记录...`);
      
      // 直接使用filter查询，与diagnoseNovelStorage保持一致
      const fullContents = await safeDbCall('fullContents', async () => 
        await db.fullContents
          .filter(item => item.novelId == numericId)
          .toArray()
      ) || [];
      
      console.log(`查询结果: 找到 ${fullContents.length} 条fullContents记录`);
      const fullContent = fullContents && fullContents.length > 0 ? fullContents[0] : null;
      
      if (fullContent) {
        console.log(`fullContent记录信息: 
          - 时间戳: ${new Date(fullContent.timestamp || 0).toLocaleString()}
          - 数据类型: ${typeof fullContent.data}
          - 数据是否为字符串: ${typeof fullContent.data === 'string'}
          - 数据长度: ${fullContent.data ? fullContent.data.length : 0}
        `);
      }
      
      if (fullContent && fullContent.data && typeof fullContent.data === 'string' && fullContent.data.length > 0) {
        console.log(`成功从fullContents表获取到小说 ${id} 的内容，长度: ${fullContent.data.length}`);
        return fullContent.data;
      }
      
      // 没有找到有效内容
      console.error(`未找到小说 ${id} 的有效缓存内容`);
      console.log(`缓存查询失败详情:
        - fullContents记录是否存在: ${fullContent ? '是' : '否'}
        - data属性是否存在: ${fullContent && fullContent.data ? '是' : '否'}
        - data是否为字符串: ${fullContent && typeof fullContent.data === 'string' ? '是' : '否'}
        - data长度是否大于0: ${fullContent && fullContent.data && fullContent.data.length > 0 ? '是' : '否'}
      `);
      
      // 如果cached标记为true但实际无内容，修复数据库状态
      try {
        const novel = await this.getNovel(id);
        if (novel && novel.cached) {
          console.warn(`小说 ${id} 被标记为已缓存，但实际无内容。修复数据库状态...`);
          await db.novels.update(id, { cached: false });
          console.log(`已将小说 ${id} 的cached标记更新为false`);
        }
      } catch (fixErr) {
        console.error('修复数据库状态失败:', fixErr);
      }
      
      throw new Error(`无法读取小说 ${id} 的缓存内容: 未找到有效内容`);
    } catch (err) {
      console.error(`获取小说缓存内容失败: ${id}`, err);
      console.log(`错误类型: ${err.name}, 错误消息: ${err.message}, 错误堆栈:\n${err.stack}`);
      throw err;
    }
  },

  // 预缓存小说列表 (用于批量缓存)
  async preCacheNovelList(novelIds, options = {}) {
    const { progressCallback } = options;
    
    try {
      if (!novelIds || novelIds.length === 0) {
        throw new Error('小说ID列表为空');
      }
      
      const total = novelIds.length;
      let current = 0;
      const results = [];
      
      // 创建更新进度的函数
      const updateProgress = (current, total) => {
        const percentage = Math.round((current / total) * 100);
        if (progressCallback) {
          progressCallback({
            current,
            total,
            percentage,
            id: novelIds[current - 1]
          });
        }
      };
      
      // 处理每个小说
      for (const novelId of novelIds) {
        try {
          // 检查是否已经缓存
          const isCached = await this.isNovelCached(novelId);
          if (isCached) {
            results.push({ id: novelId, status: 'already_cached' });
            current++;
            updateProgress(current, total);
            continue;
          }
          
          // 获取小说信息
          const novel = await this.getNovel(novelId);
          if (!novel) {
            results.push({ id: novelId, status: 'error', error: '小说不存在' });
            current++;
            updateProgress(current, total);
            continue;
          }
          
          // 从API获取完整内容
          const content = await novelsApi.getFullNovelContent(novelId);
          if (!content || !content.content) {
            throw new Error('获取小说内容失败');
          }
          
          // 缓存小说
          await this.cacheNovel(novel, content.content);
          
          results.push({ id: novelId, status: 'success' });
        } catch (err) {
          console.error(`缓存小说失败: ${novelId}`, err);
          results.push({ id: novelId, status: 'error', error: err.message || '未知错误' });
        }
        
        current++;
        updateProgress(current, total);
      }
      
      return {
        totalProcessed: current,
        totalSuccess: results.filter(r => r.status === 'success').length,
        totalAlreadyCached: results.filter(r => r.status === 'already_cached').length,
        totalErrors: results.filter(r => r.status === 'error').length,
        details: results
      };
    } catch (err) {
      console.error('批量缓存小说失败:', err);
      throw err;
    }
  },
  
  // 预缓存指定小说
  async preCacheNovel(id, priority = 'low') {
    try {
      if (await this.isNovelCached(id)) {
        console.log(`小说 ${id} 已经缓存，无需预缓存`);
        return { status: 'already_cached', id };
      }
      
      // 添加到缓存队列
      await safeDbCall('cacheQueue', async () => {
        await db.cacheQueue.put({
          id,
          priority, // high, medium, low
          requestTime: Date.now(),
          status: 'pending'
        });
      });
      
      console.log(`小说 ${id} 已添加到预缓存队列，优先级: ${priority}`);
      return { status: 'queued', id };
    } catch (err) {
      console.error(`预缓存小说 ${id} 失败:`, err);
      return { status: 'error', id, error: err.message };
    }
  },
  
  // 获取缓存队列
  async getCacheQueue() {
    return await safeDbCall('cacheQueue', async () => db.cacheQueue.toArray()) || [];
  },
  
  // 获取备份列表
  async getBackups() {
    return await safeDbCall('backups', async () => 
      db.backups.orderBy('timestamp').reverse().toArray()
    ) || [];
  },
  
  // 获取缓存统计
  async getCacheStats() {
    try {
      // 检查小说表是否存在
      const cachedNovels = await safeDbCall('novels', async () => {
        const allNovels = await db.novels.toArray();
        return allNovels.filter(novel => novel && novel.cached === true).length;
      }) || 0;
      
      // 获取内容大小
      let totalSize = 0;
      
      // 检查内容表
      const fullContents = await safeDbCall('fullContents', async () => 
        db.fullContents.toArray()
      ) || [];
      
      // 计算内容大小
      for (const content of fullContents) {
        if (content && content.data && typeof content.data === 'string') {
          totalSize += content.data.length;
        }
      }
      
      // 转换为MB
      const sizeMB = (totalSize / (1024 * 1024)).toFixed(2);
      
      return {
        cachedNovels,
        fullContentsCount: fullContents.length,
        totalSize,
        sizeMB,
        estimatedSpace: `${sizeMB} MB`
      };
    } catch (err) {
      console.error('获取缓存统计失败:', err);
      // 返回安全的默认值
      return { 
        cachedNovels: 0,
        fullContentsCount: 0,
        totalSize: 0,
        sizeMB: 0,
        estimatedSpace: '0 MB'
      };
    }
  },
  
  // 处理缓存队列 (调用此方法执行实际缓存)
  async processCacheQueue(limit = 2) {
    try {
      // 先获取高优先级任务，再获取中优先级，最后是低优先级
      const highPriorityTasks = await db.cacheQueue
        .where('priority').equals('high')
        .and(item => item.status === 'pending')
        .limit(limit)
        .toArray();
      
      const mediumPriorityTasks = await db.cacheQueue
        .where('priority').equals('medium')
        .and(item => item.status === 'pending')
        .limit(limit - highPriorityTasks.length)
        .toArray();
      
      const lowPriorityTasks = await db.cacheQueue
        .where('priority').equals('low')
        .and(item => item.status === 'pending')
        .limit(limit - highPriorityTasks.length - mediumPriorityTasks.length)
        .toArray();
      
      const tasksToProcess = [...highPriorityTasks, ...mediumPriorityTasks, ...lowPriorityTasks].slice(0, limit);
      
      if (tasksToProcess.length === 0) {
        console.log('缓存队列为空，无需处理');
        return [];
      }
      
      console.log(`开始处理 ${tasksToProcess.length} 个缓存任务`);
      
      // 标记任务为处理中
      for (const task of tasksToProcess) {
        await db.cacheQueue.update(task.id, { 
          status: 'processing', 
          startTime: Date.now() 
        });
      }
      
      // 后台处理
      const processPromises = tasksToProcess.map(async (task) => {
        try {
          // 这里需要替换为实际的从API获取内容的代码
          // 模拟从外部API获取小说
          const novelsApi = window.novelsApiRef; // 假设全局引用API
          if (!novelsApi) {
            throw new Error('API引用不可用');
          }
          
          // 获取小说信息
          const novel = await novelsApi.getNovel(task.id);
          if (!novel) {
            throw new Error('小说不存在');
          }
          
          // 标记为下载中
          await db.cacheQueue.update(task.id, { status: 'downloading' });
          
          // 模拟获取内容
          let allContent = '';
          const totalChunks = novel.chunks || 1;
          
          await this.updateCacheInfo(task.id, {
            lastCached: Date.now(),
            downloadProgress: 0,
            complete: false
          });
          
          for (let i = 0; i < totalChunks; i++) {
            const chunk = await novelsApi.getNovelChunk(task.id, i);
            if (chunk && chunk.data) {
              allContent += chunk.data;
            }
            
            // 更新进度
            await this.updateCacheInfo(task.id, {
              downloadProgress: ((i + 1) / totalChunks) * 100
            });
            
            // 更新队列状态
            await db.cacheQueue.update(task.id, { 
              progress: ((i + 1) / totalChunks) * 100
            });
          }
          
          // 缓存内容
          await this.cacheNovel(novel, allContent);
          
          // 更新队列状态为完成
          await db.cacheQueue.update(task.id, { 
            status: 'completed',
            completedTime: Date.now(),
            progress: 100
          });
          
          console.log(`小说 ${task.id} 缓存完成`);
          return { id: task.id, status: 'completed' };
        } catch (err) {
          console.error(`处理缓存任务 ${task.id} 失败:`, err);
          
          // 更新任务状态为失败
          await db.cacheQueue.update(task.id, { 
            status: 'failed',
            error: err.message,
            failedTime: Date.now()
          });
          
          return { id: task.id, status: 'failed', error: err.message };
        }
      });
      
      return await Promise.all(processPromises);
    } catch (err) {
      console.error('处理缓存队列失败:', err);
      return [];
    }
  },
  
  // 备份已缓存的小说数据
  async backupCachedNovels(options = {}) {
    try {
      const cachedNovels = await db.novels
        .where('cached').equals(true)
        .toArray();
      
      if (cachedNovels.length === 0) {
        return { status: 'no_data', message: '没有已缓存的小说数据' };
      }
      
      // 准备备份数据
      const backup = {
        timestamp: Date.now(),
        version: '1.0',
        count: cachedNovels.length,
        novels: [],
        options
      };
      
      // 获取每本小说的数据
      for (const novel of cachedNovels) {
        // 是否包含内容（可选）
        let novelData = {
          info: novel
        };
        
        // 如果需要备份章节信息
        if (options.includeChapters !== false) {
          const chapters = await chapterOperations.getNovelChapters(novel.id);
          novelData.chapters = chapters;
        }
        
        // 如果需要备份阅读进度
        if (options.includeProgress !== false) {
          const progress = await progressOperations.getProgress(novel.id);
          if (progress) {
            novelData.progress = progress;
          }
        }
        
        // 如果需要备份内容（会导致文件很大）
        if (options.includeContent === true) {
          const content = await this.getNovelContent(novel.id);
          novelData.content = content;
        }
        
        backup.novels.push(novelData);
      }
      
      // 创建备份记录
      await db.backups.add({
        id: `backup_${Date.now()}`,
        timestamp: backup.timestamp,
        count: backup.count,
        size: JSON.stringify(backup).length,
        data: backup
      });
      
      return { 
        status: 'success', 
        backup: {
          id: `backup_${backup.timestamp}`,
          timestamp: backup.timestamp,
          count: backup.count
        }
      };
    } catch (err) {
      console.error('备份缓存小说失败:', err);
      return { status: 'error', error: err.message };
    }
  },
  
  // 从备份中恢复
  async restoreFromBackup(backupId) {
    try {
      const backup = await db.backups.get(backupId);
      
      if (!backup || !backup.data) {
        throw new Error('备份不存在或数据无效');
      }
      
      // 开始恢复
      await db.transaction('rw', [db.novels, db.chapters, db.contents, db.readingProgress], async () => {
        for (const novelData of backup.data.novels) {
          const novel = novelData.info;
          
          // 恢复小说信息
          await db.novels.put(novel);
          
          // 恢复章节信息
          if (novelData.chapters) {
            await chapterOperations.addChapters(novelData.chapters);
          }
          
          // 恢复阅读进度
          if (novelData.progress) {
            await progressOperations.saveProgress(
              novelData.progress.novelId,
              novelData.progress.chapterId,
              novelData.progress.position,
              novelData.progress.timestamp,
              novelData.progress.totalProgress
            );
          }
          
          // 恢复内容
          if (novelData.content) {
            await this.cacheNovel(novel, novelData.content);
          }
        }
      });
      
      return { status: 'success', count: backup.data.novels.length };
    } catch (err) {
      console.error('从备份恢复失败:', err);
      return { status: 'error', error: err.message };
    }
  }
};

/**
 * 章节操作
 */
export const chapterOperations = {
  // 添加章节
  async addChapters(chapters) {
    return await safeDbCall('chapters', async () => db.chapters.bulkPut(chapters));
  },

  // 获取小说的所有章节
  async getNovelChapters(novelId) {
    return await safeDbCall('chapters', async () => 
      db.chapters.where('novelId').equals(novelId).sortBy('position')
    ) || [];
  },

  // 获取特定章节
  async getChapter(id) {
    return await safeDbCall('chapters', async () => db.chapters.get(id));
  }
};

/**
 * 阅读进度操作
 */
export const progressOperations = {
  // 保存阅读进度
  async saveProgress(novelId, chapterId, position, timestamp = Date.now(), totalProgress = 0) {
    return await safeDbCall('readingProgress', async () => {
      await db.readingProgress.put({
        novelId,
        chapterId,
        position,
        timestamp: timestamp,
        totalProgress: totalProgress
      });
    });
  },

  // 获取阅读进度
  async getProgress(novelId) {
    return await safeDbCall('readingProgress', async () => 
      db.readingProgress.get(novelId)
    );
  },
  
  // 获取所有阅读进度
  async getAllProgress() {
    return await safeDbCall('readingProgress', async () => 
      db.readingProgress.toArray()
    ) || [];
  },
  
  // 获取最近阅读的小说列表
  async getRecentReadingList(limit = 10) {
    return await safeDbCall('readingProgress', async () => {
      try {
        // 使用更安全的查询方式，避免索引查询问题
        const allProgress = await db.readingProgress.toArray();
        
        // 在内存中排序
        return allProgress
          .sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0))
          .slice(0, limit);
      } catch (error) {
        console.error('获取最近阅读记录失败:', error);
        // 返回空数组而不是抛出错误，避免UI崩溃
        return [];
      }
    }) || [];
  },
  
  // 更新阅读时间戳（用于更新最近阅读时间而不改变其他信息）
  async updateTimestamp(novelId, timestamp = Date.now()) {
    return await safeDbCall('readingProgress', async () => {
      const progress = await this.getProgress(novelId);
      if (progress) {
        progress.timestamp = timestamp;
        await db.readingProgress.put(progress);
      }
    });
  },
  
  // 导出阅读进度
  async exportProgress() {
    try {
      const allProgress = await this.getAllProgress();
      return {
        timestamp: Date.now(),
        version: '1.0',
        count: allProgress.length,
        data: allProgress
      };
    } catch (err) {
      console.error('导出阅读进度失败:', err);
      return { error: err.message };
    }
  },
  
  // 导入阅读进度
  async importProgress(progressData) {
    try {
      if (!progressData || !progressData.data || !Array.isArray(progressData.data)) {
        throw new Error('无效的进度数据');
      }
      
      return await safeDbCall('readingProgress', async () => {
        await db.transaction('rw', db.readingProgress, async () => {
          for (const progress of progressData.data) {
            await db.readingProgress.put(progress);
          }
        });
        
        return { status: 'success', count: progressData.data.length };
      }) || { status: 'error', error: '数据库操作失败' };
    } catch (err) {
      console.error('导入阅读进度失败:', err);
      return { status: 'error', error: err.message };
    }
  }
}; 